/**
 * Copyright 2016 vip.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * </p>
 **/

package spring.cloud.tasks.api.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Utils for saturn console.
 *
 * @author kfchu
 */
public class SaturnConsoleUtils {


    public static void exportFile(HttpServletResponse response, File srcFile, String exportFileName,
                                  boolean deleteTmpFile) throws RuntimeException {
        try (InputStream inputStream = new FileInputStream(srcFile)) {
            exportFile(response, inputStream, exportFileName);
        } catch (IOException e) {
            throw new RuntimeException("file not found:" + srcFile.getName(), e);
        } finally {
            if (deleteTmpFile && srcFile != null) {
                srcFile.delete();
            }
        }
    }

    public static void exportFile(HttpServletResponse response, InputStream inputStream, String exportFileName)
            throws RuntimeException {
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(exportFileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));

            try (BufferedInputStream bis = new BufferedInputStream(inputStream);
                 BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
